package org.casper.netty.nettydemo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class TimeServer {
	
	public void bind(int port) throws Exception{
		//配置服务端的NIO线程组:
		//创建2个原因：用于服务端接收客户端的连接，另一个进行SocketChannel的读写
		EventLoopGroup bossGroup =  new NioEventLoopGroup();
		EventLoopGroup workerGroup =  new NioEventLoopGroup();
		try {
			//ServerBootstrap是Netty用于启动NIO服务端的辅助的启动类，
			ServerBootstrap b = new ServerBootstrap();
			/*
			 * 服务端启动辅助类的配置
			 */
			b.group(bossGroup, workerGroup)
			.channel(NioServerSocketChannel.class)	//设置Channel的类型
			.option(ChannelOption.SO_BACKLOG, 1024)	//设置TCP的参数
			.childHandler(new ChildChannelHandler());//处理IO事件，例如记录日志，对消息进行编解码
			
			//绑定端口 同步等待成功，channelFuture主要用于异步操作的通知回调
			ChannelFuture f = b.bind(port).sync();
			
			//等待服务端监听端口的关闭，等待服务链路关闭后，main函数才退出
			f.channel().closeFuture().sync();
		}finally {
			//优雅的退出  释放资源
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	
	private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{
		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			ch.pipeline().addLast(new TimeServerHandler());
		}
	}
	
	public static void main(String[] args) throws Exception {
		int port = 8080;
		if(args != null && args.length >0){
			try {
				port = Integer.valueOf(args[0]);
			} catch (NumberFormatException e) {
			}
		}
		new TimeServer().bind(port);
	}
}
